package com.jiangnan.view;

import com.jiangnan.service.LoginService;
import com.jiangnan.utils.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *登入窗口
 * @author chenliang
 * @email wschenliang@aliyun.com
 */
public class LoginFrame extends BaseFrame{

    private static final Font FONT = new Font("宋体", Font.BOLD, 19);

    private static JTextField userText;
    private static JPasswordField passwordText;
    private final LoginService loginService = LoginService.newInstance();


    public LoginFrame() {
        this.setAlwaysOnTop(true);
        this.setAutoRequestFocus(false);
        this.setIconImage(new ImageIcon(getClass().getResource("/image/wireshark.png")).getImage());
        this.setTitle("欢迎登入SimpleSniffer");
        this.setSize(380, 250);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        this.add(getLoginPane());
    }

    private JPanel getLoginPane() {
        JPanel panel = new JPanel();
        panel.setLayout(null);

        JLabel userLabel = new JLabel("用户名：");
        userLabel.setBounds(35,20,100,30);
        userLabel.setFont(FONT);
        panel.add(userLabel);

        JLabel passwordLabel = new JLabel("密 码：");
        passwordLabel.setBounds(35,70,100,30);
        passwordLabel.setFont(FONT);
        panel.add(passwordLabel);

        userText = new JTextField(20);
        userText.setBounds(140,20,165,30);
        panel.add(userText);

        passwordText = new JPasswordField(20);
        passwordText.setBounds(140,70,165,30);
        passwordText.setEchoChar('*');
        panel.add(passwordText);

        JButton loginButton = new JButton("登入");
        loginButton.setBounds(133, 130, 100, 40);
        loginButton.setFont(FONT);
        loginButton.setActionCommand("Enter");
        loginButton.addActionListener(new LoginButtonAction());
        panel.add(loginButton);
        return panel;
    }


    private class LoginButtonAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            String userName = userText.getText();
            String password = new String(passwordText.getPassword());
            if (StringUtils.hasBlank(userName, password)) {
                alert("请输入正确的用户名和密码");
            }
            boolean result = loginService.checkUser(userName, password);
            if (result) {
                dispose();
                try {
                    Thread.sleep(300);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                HomeFrame.frame().setVisible(true);
            } else {
                alert("用户名和密码不正确！！");
            }
        }
    }
}
